package controller;

import model.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UserLogin", value = "/user_login")
public class UserLoginServlet extends HttpServlet {
    UserService us = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;Charset=utf-8");
        String ue = request.getParameter("ue");
        String password = request.getParameter("password");
        User user = us.login(ue, password);
        if (user == null) {
            String message = "用户名或者密码错误，请重新登录！";
            request.setAttribute("failMsg", message);
            request.getRequestDispatcher("user_login.jsp").forward(request, response);
        } else {
            request.getSession().setAttribute("user", user);
            response.sendRedirect("user_center.jsp");
        }
    }
}
